package gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.border.EtchedBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import users.Manager;
import java.lang.Integer;

public class ProcessDeliveryOrder extends JPanel{

	private static final long serialVersionUID = -4007098762333594465L;

	private JPanel rPanel;
	private JTable rTable;
	private JButton selectOrderButton;
	
	private JPanel rDPanel;
	private JTable rDTable;
	private JButton sendOrder;
	
	private int receiptRow = -1, rDetailRow = -1;
	private int receiptID;
	private Manager manager;
	
	public ProcessDeliveryOrder(Manager manager){
		this.manager = manager;
		
		receiptTable();
		
		rDetailsTable();
	}
	
	private void receiptTable(){
		this.removeAll();
		
		rPanel = new JPanel(new FlowLayout());
		TitledBorder title = BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Order List");
		rPanel.setBorder(title);
		
		// The column names of the item table
		String[] columnNames = {"receiptID", 
								"purchaseDate",
								"cid",
								"name",
								"card#",
								"expire",
								"expectedDate",
								"deliveredDate",};
		
		// query PurchaseOrder table and get ResultSet
		ResultSet result = null;
		try {
			result = manager.listOrders();
		} catch (SQLException e1) {
			System.out.println("Could not query Purchase Table.");
			e1.printStackTrace();
		}
		
		// turn ResultSet into a JTable
		try {
			rTable = rsToTable(result, columnNames);
			result.close();
		} catch (SQLException e) {
			System.out.println("Could not query Purchase Table.");
			e.printStackTrace();
		}
        
		// add a scrolling panel
		JScrollPane scrollPane = new JScrollPane(rTable);
        rPanel.add(scrollPane);
        
        rTable.getSelectionModel().addListSelectionListener(new RowListener());
        
        // add to basket button
        selectOrderButton = new JButton("View Selected Order");
        selectOrderButton.addActionListener(new SelectOrder());
		rPanel.add(selectOrderButton);
        
		add(rPanel);
	}
	
	private void rDetailsTable(){
		rDPanel = new JPanel(new FlowLayout());
		TitledBorder title = BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Order Detail List");
		rDPanel.setBorder(title);
				
		rDTable = new JTable();
		
		JScrollPane scrollPane = new JScrollPane(rDTable);
        rDPanel.add(scrollPane);

	}
	
	// Returns a 2-D Object Array from the ResultSet.
	private static JTable rsToTable(ResultSet result, String[] columnNames) throws SQLException{
		List<Object[]> rows = new ArrayList<Object[]>();
		
		while (result.next()){
			Object[] row = new Object[columnNames.length+1];
			
			for (int i=0; i<columnNames.length; i++){
				Object value = result.getObject(columnNames[i]);
				row[i] = value;
			}			
			rows.add(row);
		}
		
		Object[][] data = new Object[rows.size()][columnNames.length+1];
		
		for (int i=0; i<rows.size(); i++){
			data[i] = rows.get(i);
		}
		
		JTable table = new JTable(data, columnNames);
		table.setPreferredScrollableViewportSize(new Dimension(500, 70));
        table.setFillsViewportHeight(true);
		
		return table;
	}
	
	// action listener for the item table selector
	private class RowListener implements ListSelectionListener {
		
		public void valueChanged(ListSelectionEvent e2) {
            if (e2.getValueIsAdjusting()) {
                return;
            }
			
            // get the item that is selected from the item table
            receiptRow = rTable.getSelectedRow();
		}
	}
	
	private class SelectOrder implements ActionListener{

		Object[][] data;
		ResultSet result;
		
		public void actionPerformed(ActionEvent e) {
			rDPanel.removeAll();
			
			String[] columnNames = {"upc",
									"quantity"};
			
			if (receiptRow == -1){
				JOptionPane.showMessageDialog(selectOrderButton,
					    "Please select an order to edit.",
					    "Order Selection Error",
					    JOptionPane.ERROR_MESSAGE);
						return;				
			} else {
				
				// Get the receiptID
				Object temp = rTable.getValueAt(receiptRow, 0);
				receiptID = Integer.parseInt(temp.toString());
				
				// Get the PurchaseItem
				try {
					result = manager.getOrderDetail(receiptID);
				} catch(SQLException e1){
					JOptionPane.showMessageDialog(selectOrderButton,
						    "Please select another order.",
						    "Try again",
						    JOptionPane.ERROR_MESSAGE);
							return;
				}
			}
			
			// convert ResultSet to a JTable
			try {
				rDTable = rsToTable(result,columnNames);
				
				result.close();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			
			// paint/repaint table
			receiptTable();
			
			rDPanel = new JPanel(new FlowLayout());
			TitledBorder title = BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED), "Order Detail List");
			rDPanel.setBorder(title);
			
			JScrollPane scrollPane = new JScrollPane(rDTable);
	        rDPanel.add(scrollPane);
	        
	        rDTable.getSelectionModel().addListSelectionListener(new RowListener());
			
	        sendOrder = new JButton("Deliver This Order");
	        sendOrder.addActionListener(new SendItem());
			rDPanel.add(sendOrder);
			
			add(rDPanel);
		}
		
	}
	
	private class SendItem implements ActionListener{

		public void actionPerformed(ActionEvent e) {
			
			boolean success=true;
			
			try {
				success = manager.deliverPurchaseItem(receiptID);
			} catch (SQLException e1) {
				e1.printStackTrace();
			}

			if (success == false){
				JOptionPane.showMessageDialog(sendOrder,
					    "Not enough stock for an item, or already delivered.",
					    "Try again when more shipment came in",
					    JOptionPane.ERROR_MESSAGE);
						return;
			} else {
				JOptionPane.showMessageDialog(sendOrder,
					    "Items are delivered",
					    "It will be shiped",
					    JOptionPane.OK_OPTION);
						receiptTable();
						return;
			}
		}
	}
	
}

